import { Injectable } from '@nestjs/common';
import { CreateLineDto } from './dto/create-line.dto';
import { UpdateLineDto } from './dto/update-line.dto';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class LineService {
  constructor(private prisma: PrismaService) {}

  async create(createLineDto: CreateLineDto) {
    return await this.prisma.line.create({ data: createLineDto });
  }

  async findAll(args: Record<string, any>) {
    const { projId } = args;
    const lines = await this.prisma.line.findMany({
      where: { projId: +projId },
      include: { Bet: true },
    });

    const data = lines.map((line) => {
      const totalSpan = line.Bet.map((bet) => bet.btSpan).reduce((acc, acu) => {
        return acc + acu;
      }, 0);
      return {
        id: line.id,
        name: line.name,
        start: line.start,
        end: line.end,
        totalSpan,
      };
    });
    return data;
  }

  async findOne(id: number) {
    return await this.prisma.line.findFirst({
      where: { id },
      include: {
        proj: true,
      },
    });
  }

  async update(id: number, updateLineDto: UpdateLineDto) {
    return await this.prisma.line.update({
      where: { id },
      data: updateLineDto,
    });
  }

  async remove(id: number) {
    return await this.prisma.line.delete({ where: { id } });
  }
}
